#!/usr/bin/python
import sys, os, Image

def make_thumb(dst, src, size = 300):
	base, ext = os.path.splitext(src)
	try:
		im = Image.open(src)
	except IOError:
		return
	mode = im.mode
	if mode not in ('L', 'RGB'):
		if mode == 'RGBA':
			# add white background
			alpha = im.split()[3]
			bgmask = alpha.point(lambda x: 255-x)
			im = im.convert('RGB')
			# paste(color, box, mask)
			im.paste((255,255,255), None, bgmask)
		else:
			im = im.convert('RGB')

	width, height = im.size
	if width == height:
		region = im
	else:
		if width > height:
			delta = (width - height)/2
			box = (delta, 0, delta+height, height)
		else:
			delta = (height - width)/2
			box = (0, delta, width, delta+width)
		region = im.crop(box)

	thumb = region.resize((size, size), Image.ANTIALIAS)
	thumb.save(dst, quality = 92)


if __name__ == '__main__':
	if (len(sys.argv) >= 3):
		dir = sys.argv[1]
		dst = sys.argv[2]
	elif (len(sys.argv) == 2):
		dir = sys.argv[1]
		dst = sys.argv[1]
	else:
		if os.path.isdir('/Volumes/Media/Pictures'):
			dst = '/Volumes/Media/Pictures'
			if os.path.isdir('/Volumes/DAT/Pictures'):
				dir = '/Volumes/DAT/Pictures'
			else:
				dir = '/Volumes/Media/Pictures'
		else:
			print 'Usage: thumb.py <SrcDir> [DstDir]'
			exit()

	files = os.listdir(dir)
	for f in files:
		dir2 = dir + '/' + f
		if (f[0] != '.') and os.path.isdir(dir2):
			files2 = os.listdir(dir2)
			files2.sort()
			for f2 in files2:
				if os.path.splitext(f2)[1] in ('.jpg', '.png'):
					src = dir2 + '/' + f2
					print 'Generate thumb for ' + src
					make_thumb(dst + '/.thumb.' + f + '.jpg', src)
					break
